<?php
/**
 * Description of AccountsUI
 *
 * @author josema
 */
class AccountsUI extends SystemInterface implements Actionable {

    public function serviceHandler($vars) {
        return $this->runService($vars[0]);
    }

    protected function service_showAccounts(){
        require_once Path::getPath('users').'UserManager.php';
        $manager = new UserManager();

        $user = $manager->getCurrentUser();

        $accounts = $user->getRelation('accounts');

        foreach ($accounts as $acc) {
            $dbf = new DataBaseFactory(new Transaction);
            $dbf->selectWhere(array('*'), 'account = '.$acc->id .' OR going_to = '.$acc->id);

            $balance = 0;
            while ($obj = $dbf->fetch()){
                if($obj->date < '2012-01-01'){
                    if($obj->type == 'Transfer' && $obj->going_to == $acc->id)
                        $balance -= $obj->amount;
                    else
                        $balance += $obj->amount;
                }
            }
            $acc->current_amount = $acc->initial_amount + $balance;
        }

        $tpl = new Template();

        $tpl->addObjects('account', $accounts);

        return $tpl->fetch('accounts.tpl');
    }

}
?>
